package com.ube.code.decode.uri;

import sun.security.rsa.RSASignature;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Xrnd on 2015/9/13.
 */
public class Decode {
    private static MessageDigest md = null;

    public static void main (String[] args) throws IOException, NoSuchAlgorithmException {
        md = MessageDigest.getInstance("MD5");

        final String sr = "d:\\deal.html";
        final String sw = "d:\\out.html";
        BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(sr), "UTF-8"));
        OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(sw), "UTF-8");


        int count = 0;
        String line;
        while (null != (line = fr.readLine())) {
            line = replace(line);
            fw.write(line);
            fw.write("\n");
            ++ count;
        }

        fr.close();
        fw.close();
    }

    public static String replace (String sb) throws UnsupportedEncodingException {
        final String pattern = "(UserGuide-zh-[^\"]+)";
        final Pattern pat = Pattern.compile(".*"+pattern+"\".*");
        Matcher matcher = pat.matcher(sb);
        String line = null;
        String match = null;
        if (matcher.matches() && (match = matcher.group(1)) != null) {
            //String rep = URLDecoder.decode(match, "UTF-8");
            //System.out.println(match+" => "+rep);
            String digest = byteArrayToHexString(md.digest(match.getBytes("UTF-8")));
            line = sb.replaceAll(pattern, digest);
        } else {
            line = sb.toString();
        }

        return line;
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
}
